package com.hjx.leetcode;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 控制线程的执行顺序
 * 解法4、ReentrantLock 的条件队列
 */
class LeetCode_1114_solution4 {

    public ReentrantLock lock = new ReentrantLock();
    public String flag = "first";

    public Condition c1 = lock.newCondition();
    public Condition c2 = lock.newCondition();


    public void first(Runnable printFirst) throws InterruptedException {
        lock.lock();
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();

        flag = "second";
        //开启second
        c1.signal();
        lock.unlock();
    }

    public void second(Runnable printSecond) throws InterruptedException {
//        System.out.println(Thread.currentThread() + " 即将挂起");

        lock.lock();
        if (flag.equals("first") || flag.equals("third")) {
            c1.await();
        }
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        //开启third
        flag = "third";
        c2.signal();
        lock.unlock();
    }

    public void third(Runnable printThird) throws InterruptedException {

//        System.out.println(Thread.currentThread() + " 即将挂起");
        lock.lock();
        if (flag.equals("first") || flag.equals("second")){
            c2.await();
        }

        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
        lock.unlock();
    }

}
